package com.guigu.tms.dispatch.job;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guigu.tms.commons.dispatch.entity.ScheduleJob;
import com.guigu.tms.commons.dispatch.entity.ScheduleJobLog;
import com.guigu.tms.dispatch.mapper.ScheduleJobLogMapper;
import com.guigu.tms.dispatch.utils.ScheduleUtils;
import com.guigu.tms.dispatch.utils.SpringContextUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

public class DispatchJob extends QuartzJobBean {


    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        ScheduleJob scheduleJob =
                (ScheduleJob) context.getMergedJobDataMap().
                        get(ScheduleUtils.JOB_PARAM_KEY);
        //记录定时任务相关的日志信息
        //封装日志对象
        ScheduleJobLog logEntity = new ScheduleJobLog();
        logEntity.setId(IdWorker.getId());
        logEntity.setJobId(Long.parseLong(scheduleJob.getId()));
        logEntity.setBeanName(scheduleJob.getBeanName());
        logEntity.setParams(scheduleJob.getParams());
        logEntity.setCreateDate(LocalDateTime.now());

        long startTime = System.currentTimeMillis();

        try{
            //通过反射调用目标对象，在目标对象中封装智能调度核心逻辑
            //获得目标对象
            Object target = SpringContextUtils.getBean(scheduleJob.getBeanName());
            //获得目标方法对象
            Method method = target.getClass().getDeclaredMethod("run", String.class, String.class, String.class, String.class);
            //通过反射调用目标对象的方法
            method.invoke(target,scheduleJob.getBusinessId(),scheduleJob.getParams(),scheduleJob.getId(),logEntity.getId().toString());
            logEntity.setStatus(1);//成功
        }catch (Exception ex){
            logEntity.setStatus(0);//失败
            logEntity.setError(ex.toString());
        }finally {
            int times = (int) (System.currentTimeMillis() - startTime);
            logEntity.setTimes(times);//耗时
            ScheduleJobLogMapper scheduleJobLogMapper=SpringContextUtils.getBean(ScheduleJobLogMapper.class);
            scheduleJobLogMapper.insert(logEntity);
        }
    }

}
